import store from "../vuex/store";
import router from "../router";
import config from "../api/config";


var bridgefunc = {
  callBridge: function (bridgeOpStr, paras, callback) {
    this.setupWebViewJavascriptBridge(function (bridge) {
      bridge.callHandler(bridgeOpStr, paras, function responseCallback(response) {
        if (callback) {
          callback(response);
        }
      })
    })
    // let webtype = store.state.webType;
    // if (webtype != '1') {
    //   if (callback) {
    //     callback(null);
    //   }
    // }
  },
  registeBridge: function (bridgeOpStr, callback) {
    this.setupWebViewJavascriptBridge(function(bridge) {
      bridge.registerHandler(bridgeOpStr, function(data, responseCallback) {
        if (callback) {
          callback(data,responseCallback);
        }
      })
    })
  },
  setupWebViewJavascriptBridge: function (callback) {
    if (window.WebViewJavascriptBridge) {
      return callback(WebViewJavascriptBridge);
    }
    if (window.WVJBCallbacks) {
      return window.WVJBCallbacks.push(callback);
    }
    window.WVJBCallbacks = [callback];
    var WVJBIframe = document.createElement('iframe');
    WVJBIframe.style.display = 'none';
    WVJBIframe.src = 'wvjbscheme://__BRIDGE_LOADED__';
    document.documentElement.appendChild(WVJBIframe);
    setTimeout(function () {
      document.documentElement.removeChild(WVJBIframe)
    }, 0)
  },
  // 尊重原数据结构，push
  customPush: function (pushData) {
    // let webtype = store.state.webType;
    // console.log(webtype)
    // if (webtype != '1') {
      store.state.pushedLength ++
      bridgefunc.vuexStorage(() => {
      })
    router.push(pushData)
      // return
    // }
    // let path = pushData.path
    // let pathBase = '/' + config.routeBase
    // if (path.indexOf(pathBase) != 0) {
    //   path = pathBase + path
    // }
    // path = path + '?'
    // let query = pushData.query
    // for (let key in query) {
    //   let value = query[key]
    //   path += key + '=' + value + '&';
    // }
    // path = path.substr(0, path.length - 1)
    // let paras = {
    //   weburl: path
    // }
    // bridgefunc.newPage(paras)
  },
  //新创建页面 jsonData里面包含跳转地址weburl、isnativetop（是否是原生上导航，不传默认是原生的）
  newPage: function (jsonData) {
    let webtype = store.state.webType;
    let weburl = jsonData.weburl
    if (typeof(weburl) == undefined) {
      console.log('传参有误')
      return
    } else if (weburl.indexOf("http") != 0) {
      weburl = config.webBase + weburl
    }
    if (webtype != '1') {
      window.location.href = weburl
      return
    }
    jsonData.weburl = weburl
    jsonData.type = 'newpage'
    jsonData.isnativetop = '1'
    bridgefunc.callBridge('phonebridge',jsonData)
  },
  resetPage: function (jsonData) {
    let webtype = store.state.webType;
    let weburl = jsonData.weburl
    if (typeof(weburl) == undefined) {
      console.log('传参有误')
      return
    } else if (weburl.indexOf("http") != 0) {
      weburl = config.webBase + weburl
    }
    // if (webtype != '1') {
    //   window.location.replace(weburl)
    //   return
    // }
    console.log('weburl',weburl)
    jsonData.weburl = weburl
    jsonData.type = 'resetpage'
    jsonData.isnativetop = '0'
    bridgefunc.callBridge('phonebridge',jsonData)
  },
  // 尊重原数据结构，返回
  customGo: function (n) {
    // let webtype = store.state.webType;
    // if (webtype == '1') {
      store.state.pushedLength += n
      bridgefunc.vuexStorage(() => {
        router.go(n)
      })
      // return
    // }
    // bridgefunc.turnBack(n)
  },
  //pop到第几层 如果n为0 或 不传则默认pop到上一层
  turnBack:function (n){
    let webtype = store.state.webType;
    let jsonData = {};
    if(n && typeof n === 'number'){
      if (webtype != '1') {
        window.history.go(n)
        return
      }
      jsonData.type = 'turnback'
      jsonData.index = n + ''
      bridgefunc.callBridge('phonebridge',jsonData)
    } else {
      if (webtype != '1') {
        window.history.go(-1)
        return
      }
      jsonData.type = 'turnback'
      bridgefunc.callBridge('phonebridge',jsonData)
    }
  },
  //支付宝授权 授权回调
  aliAuth:function (callback) {
    let jsonData = {};
    jsonData.type = 'commonargs'
    bridgefunc.callBridge('phonebridge',jsonData,callback)
  },
  //百度导航  传入起始点startlong startlat 和终点的经纬度 endlong  endlat
  baiduNav:function (jsonData) {
    if(!jsonData||!jsonData.startlong || !jsonData.startlat || !jsonData.endlong || !jsonData.endlat){
      console.log('传参有误')
      return;
    }
    jsonData.type = 'nav'
    bridgefunc.callBridge('phonebridge',jsonData)
  },
  //页面展示
  registePageShow:function (callback) {
    bridgefunc.registeBridge('pagewillshow', function () {
      callback()
    })
  },
  //存item
  setItem:function (key,value,callback) {
    let webtype = store.state.webType;
    if (webtype != '1') {
      window.localStorage.setItem(key,value);
      if(callback){
        callback();
      }
      return
    }else {
      let jsonData = {};
      jsonData.type = 'storeitem'
      jsonData.key = key;
      jsonData.value = value;
      bridgefunc.callBridge('phonebridge',jsonData,callback)
    }
  },
  setItems:function (keyvalues,callback) {
    let webtype = store.state.webType;
    if (webtype != '1') {
      for(let i = 0; i <keyvalues.length;i++){
        let keyvalue = keyvalues[i];
        window.localStorage.setItem(keyvalue.key,keyvalue.value);
      }
      if(callback){
        callback();
      }
      return
    }else {
      let jsonData = {};
      jsonData.type = 'storeitems'
      jsonData.keyvalues = keyvalues;
      bridgefunc.callBridge('phonebridge',jsonData,callback)
    }
  },
  removeItem:function (key,callback) {
    let webtype = store.state.webType;
    if (webtype != '1') {
      window.localStorage.removeItem(key);
      if(callback){
        callback();
      }
      return
    }else {
      let jsonData = {};
      jsonData.type = 'removeitem'
      jsonData.key = key;
      bridgefunc.callBridge('phonebridge',jsonData,callback)
    }
  },
  getItem:function (key,callback) {
    let webtype = store.state.webType;
    if (webtype != '1') {
      if(callback){
        callback(window.localStorage.getItem(key));
      }
      return
    } else {
      let jsonData = {};
      jsonData.type = 'getitem'
      jsonData.key = key;
      bridgefunc.callBridge('phonebridge',jsonData,callback);
    }
  },
  getItems:function (keys,callback) {
    let webtype = store.state.webType;
    if (webtype != '1') {
      if(callback){
        let result = {};
        for(let i = 0; i <keys.length;i++){
          let key = keys[i];
          result[key] = window.localStorage.getItem(key);
        }
        callback(result);
      }
      return
    }else {
      let jsonData = {};
      jsonData.type = 'getitems'
      jsonData.keys = keys;
      bridgefunc.callBridge('phonebridge',jsonData,callback);
    }
  },
  vuexStorage: function (callback) {
    let jsonString = encodeURIComponent(JSON.stringify(store.state))
    // setItem:function (key,value,callback)
    bridgefunc.setItem('vuex', jsonString, callback)
  },
  vuexRead: function (callback) {
    bridgefunc.getItem('vuex', function (result) {
      // console.log(result)
      if (!result) {
        if (callback) {
          callback()
        }
        return ;
      }
      let jsonString = decodeURIComponent(result);
      let jsonData = JSON.parse(jsonString)
      if (jsonData) {
        store.replaceState(jsonData)
      } else {
        bridgefunc.vuexStorage()
      }
      if (callback) {
        callback()
      }
    })
  },
  _loopState: function(jsonData,toData){
    for(let key in jsonData){
      if(typeof jsonData[key] != 'object'){
        toData[key] = jsonData[key];
      }else {
        this._loopState(jsonData[key],toData[key]);
      }
    }
  },
  //微信分享 title标题 sharetext副标题 imageurl图标url   detailurl链接url
  wechatShare:function (jsonData) {
    jsonData.type = 'wechatshare',
      bridgefunc.callBridge('phonebridge',jsonData);
  }
}

export default bridgefunc
